package com.itheima.reggie.interceptor;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.util.BaseContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 拦截器
 */
@Component
@Slf4j
public class LoginCheckInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        log.info("拦截到请求:{}", requestURI);

        Object emp = request.getSession().getAttribute("emp");
        if (emp != null) {
            log.info("已登录:{}", request.getSession().getAttribute("emp"));
            Employee employee = (Employee) request.getSession().getAttribute("emp");
            Long id = employee.getId();
            BaseContext.setId(id);
            return true;
        }

        Long userId = (Long) request.getSession().getAttribute("user");
        if (userId != null) {
            log.info("已登录:{}", request.getSession().getAttribute("user"));
            BaseContext.setId(userId);
            return true;
        }

        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        log.info("用户未登录");
        return false;

    }
}
